/*
*    Phantom v2.0 GUI Automation Software
*    Copyright (C) 2009  John C. Van Arsdall (john@phantomtest.com)
*
*    This program is free software; you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation; either version 2 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License along
*    with this program; if not, write to the Free Software Foundation, Inc.,
*    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
// Console.cpp: implementation of the CConsole class.
//
//////////////////////////////////////////////////////////////////////

#include "ssi_console.h"
#include "ssi_interpreter.h"


//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CConsole::CConsole(ssi_stream *an_input, ssi_stream *an_output)
{
	output = an_output;
	input = an_input;

  Engine = SSI_NULL;
  Interp = SSI_NULL;
  CurrLine = SSI_NULL;

  LineCtr = 0;

  Interp = new CInterpreter((CInput*)this);
  Engine = new CEngine;

	Engine->SetOutDisplay(output);
  Interp->SetOutDisplay(output);

  Interp->SetEngine(Engine);
  Engine->SetInterpreter(Interp);

	RunMode = NORMAL_MODE;  // Default to NORMAL_MODE
}

CConsole::~CConsole()
{
	delete Engine;
	delete Interp;
}

SSI_INT64 CConsole::Loop()
{
  SetInputName(String("Console"));
	SetFileName(String(""));

  while(WaitPrompt())
  {
  }
  zap(Interp);
  zap(Engine);
  return 0;
}

SSI_BOOL CConsole::WaitPrompt()
{
	ScriptNode* aNode = 0;
  CScriptLine aLine;
	
	aNode = GetLine(aLine);
	if(!aNode) return 0;

  if(aLine.Line == "stop")
  {
    return 0;
  }

  Interp->Interpret(aLine.Line, aNode);

	if(Interp->GetStopState()){
		return 0;
	}

  return 1;
}

SSI_BOOL CConsole::GetNextLine(CScriptLine& Ret)
{
	ScriptNode* aNode = 0;
  aNode = GetLine(Ret);
	if(!aNode){
		return 0;
	}
  return 1;
}

ScriptNode* CConsole::GetLine(CScriptLine& RetLine)
{
  if(CurrLine)
  {
    CurrLine = CurrLine->next();
    if(CurrLine)
    {
      CurrLine->Get(RetLine);
			return CurrLine;
    }
  }
  
  SSI_CHAR Temp[MAX_SSI_CHARS];
  
  LineCtr++;

	String s;
	s.Format("%d >>", LineCtr);
	output->Disp(s.Str());
	if(input->getline(Temp, MAX_SSI_CHARS) < 0){
		Interp->SetStopFlag();
		return 0;
	}
  
  RetLine.Line = Temp;
  RetLine.LineNum = LineCtr;

  CurrLine = PushLine(RetLine);//Lines.push(RetLine);
  return CurrLine;
}




